﻿using System;
using System.Net;
using SocialPlatformSDK.Hammock.Authentication.OAuth;
using SocialPlatformSDK.Hammock.Web;
using SocialPlatformSDK.Model;
using SocialPlatformSDK.Services.Util;
using SocialPlatformSDK.Deserializer;
using SocialPlatformSDK.Hammock;
using System.Collections.Generic;
using SocialPlatformSDK.Hammock.Silverlight.Compat;
using System.Text;

namespace SocialPlatformSDK.Services
{
    public interface IOAuthService
    {
        void GetAccessTokenRequest(CodeToken code, Action<Callback<AccessToken>> callback);
        String GetCallBackUrl();
        IOAuthConfigruation GetOAuthConfigruation();
    }

    /// <summary>
    /// OAuthService 包含了 OAuth 相关 API.
    /// R 是 RequestToken A AccessToken O OAuthConfigruationBase
    /// </summary>
    /// 
    public sealed class OAuthService<A> : IOAuthService
        where A : AccessToken, new()
    {
        //private IAPIpath _apiPath;
        private IOAuthConfigruation OAuthConfigruationBase;
        public OAuthService(IOAuthConfigruation oAuthConfigruation )
        {
     
            OAuthConfigruationBase = oAuthConfigruation;
        }


        public String GetCallBackUrl()
        {
            return OAuthConfigruationBase.CallBackUrl;
        }

        public IOAuthConfigruation GetOAuthConfigruation()
        {
            return OAuthConfigruationBase;
        }
        /// <summary>
        /// 获取RequestToken.
        /// </summary>
        /// <param name="callbackUrl">需要回调的Url(用于判断是否验证成功).</param>
        /// <param name="callback">回调返回 RequestToken 对象.</param>
        //public void GetRequestTokenRequest(string callbackUrl, Action<Callback<RequestToken>> callback)
        //{
        //    this.GetRequestTokenRequest(callbackUrl, (request, response, userState) =>
        //    {

        //        if (callback != null)
        //        {
        //            R token = new R();
        //            token.LoadToken(response.Content);
        //            callback(new Callback<RequestToken>(token));
        //        }
        //    });
        //}

        //private void GetRequestTokenRequest(string callback, RestCallback handler)
        //{
            
        //    RestClient client = new RestClient()
        //    {
        //        Authority = _apiPath.APIUrl,
        //        HasElevatedPermissions = true,
        //        //Credentials = OAuthCredentials.ForTencentRequestToken(OAuthConfigruationBase.APP_KEY, OAuthConfigruationBase.APP_SECRET, callback)
        
        //    };

        //    RestRequest request = new RestRequest()
        //    {
        //        Path = _apiPath.GetRequestToken,
        //        Method = WebMethod.Get
        //    };

        //    client.BeginRequest(request, new RestCallback(handler));
        //}

        private void GetAccessTokenRequest(CodeToken code, RestCallback handler)
        {
           
            RestClient client = new RestClient()
            {
                Authority = OAuthConfigruationBase.Authority,
                HasElevatedPermissions = true,
                
            };

            RestRequest request = new RestRequest()
            {
                Path = OAuthConfigruationBase.GetAccessToken,
                Method = WebMethod.Post,
                DecompressionMethods = DecompressionMethods.GZip,
                Encoding = Encoding.UTF8,
            };
            request.AddParameter("client_id", OAuthConfigruationBase.APP_KEY);
            request.AddParameter("client_secret", OAuthConfigruationBase.APP_SECRET);
            request.AddParameter("grant_type", "authorization_code");
            request.AddParameter("redirect_uri", OAuthConfigruationBase.CallBackUrl);
            request.AddParameter("code", code.Code);

            client.BeginRequest(request, new RestCallback(handler));
        }

        /// <summary>
        /// 获取AccessToken.
        /// </summary>
        /// <param name="requestToken">填入在 GetRequestTokenRequest 里取得的RequestToken.</param>
        /// <param name="callback">回调返回AccessToken.</param>
        public void GetAccessTokenRequest(CodeToken code, Action<Callback<AccessToken>> callback)
        {
            this.GetAccessTokenRequest(code,(request, response, userState) =>
            {
                if (callback != null)
                {   
                    OAuthConfigruationBase.AccessToken.LoadToken(response.Content);
                    AccessToken Accesstoken = OAuthConfigruationBase.AccessToken ;
                    callback(new Callback<AccessToken>(Accesstoken));
                }
            });
        }
    }
}
